import { SetupContext, computed, ref } from "vue";
import { InputGroupProps } from "../input-group.props";
import { UseClear, UseTextBox } from "./types";

export function useClear(
    props: InputGroupProps,
    context: SetupContext,
    useTextBoxComposition: UseTextBox
): UseClear {
    const hasShownClearButton = ref(false);
    const shouldShowClearButton = computed(() => props.enableClear && !props.readonly && !props.disabled);
    const { changeTextBoxValue, isEmpty } = useTextBoxComposition;

    const clearButtonClass = computed(() => ({
        'input-group-text': true,
        'input-group-clear': true
    }));

    const clearButtonStyle = computed(() => {
        const styleObject = {
            width: '24px',
            display: hasShownClearButton.value ? 'flex' : 'none'
        } as Record<string, any>;
        return styleObject;
    });

    /** 清空输入框中的值 */
    function onClearValue($event: MouseEvent) {
        $event.stopPropagation();
        if (shouldShowClearButton.value) {
            changeTextBoxValue('');
            hasShownClearButton.value = false;
            context.emit('clear');
        }
    }

    function onMouseEnter(event: MouseEvent) {
        if (shouldShowClearButton.value && !isEmpty.value) {
            hasShownClearButton.value = true;
        }
    }

    function onMouseLeave(event: MouseEvent) {
        if (shouldShowClearButton.value) {
            hasShownClearButton.value = false;
        }
    }

    return { clearButtonClass, clearButtonStyle, hasShownClearButton, onClearValue, onMouseEnter, onMouseLeave, shouldShowClearButton };
}
